//
//  HomeRootViewController.m
//  quanminzhekou
//
//  Created by zxl on 15/1/7.
//  Copyright (c) 2015年 zhongqinglongtu. All rights reserved.
//

#import "HomeRootViewController.h"
#import "CommonTableViewCell.h"
#import "HomeHeaderView.h"
#import "CategoryViewController.h"
#import "DetailViewController.h"
#import "CommonEngine.h"
#import "CommonCellViewModel.h"
#import "FocusViewModel.h"
#import "CustomTableViewController.h"
#import "UpdateView.h"

@interface HomeRootViewController ()
@property (nonatomic, weak) IBOutlet UpdateView* updateView;

@property (nonatomic) NSMutableArray* homeDataArr;
@property (nonatomic) NSMutableArray* homeFocusArr;
@property (nonatomic) HomeHeaderView* headerView;
@property (nonatomic) NSTimer* autoScrollingtime;
@property (nonatomic) MKNetworkOperation* homeOperation;
@property (nonatomic) MKNetworkOperation* focusOperation;
@property (nonatomic) MKNetworkOperation* upnumOperation;
@property (nonatomic) BOOL isUpdateFocus;
@end

@implementation HomeRootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.viewControllerType = ViewControllerNormalType;
    
    _homeDataArr = [[NSMutableArray alloc] init];
    _homeFocusArr = [[NSMutableArray alloc] init];
    
    _headerView = [[HomeHeaderView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), CGRectGetWidth([UIScreen mainScreen].bounds) / 320.0 * 193.5)];
    _headerView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    self.tableView.tableHeaderView = _headerView;
    
    __weak typeof(self) weakSelf = self;
    _headerView.tapBtnHandler = ^(NSString* str) {
        CategoryViewController* controller = [weakSelf.storyboard instantiateViewControllerWithIdentifier:@"CategoryViewController"];
        controller.title = str;
        [weakSelf.navigationController pushViewController:controller animated:YES];
//        [weakSelf.tabBarController setTabBarHidden:YES animated:YES];
    };
    
    self.engineModel.zqStr = @"1";
    
    [self headerViewScrollViewAddTimer];
    
    self.isUpdateFocus = YES;
    [self updateData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [self.homeOperation cancel];
    [self.focusOperation cancel];
    [self.upnumOperation cancel];
}

#pragma mark - super
- (void)updateData {
    [super updateData];
    
    [self updateHomeData];
    
    if (self.isUpdateFocus) {
        [self updateHomeFocus];
    } else {
        self.isUpdateFocus = YES;
    }
    
}

#pragma mark -
- (void)updateHomeData {
    if (_homeOperation.isExecuting) {
        return;
    }
    
    __weak typeof(self) weakSelf = self;
    
    NSString* path = [[CommonEngine sharedInstance] urlPathForDataWithDictionary:self.engineModel.dic];
    
    _homeOperation = [[CommonEngine sharedInstance] getOperationWithURLPath:path shouldCache:NO completionHandler:^(NSDictionary *result) {
        NSNumber* status = [result objectForKey:@"status"];
        NSNumber* count = [result objectForKey:@"count"];
        if (1 == status.integerValue) {
            
            NSMutableArray* res = [NSMutableArray new];
            
            NSArray* arr = [result objectForKey:@"res"];
            for (NSDictionary* dic in arr) {
                CommonCellModel* model = [[CommonCellModel alloc] initWithDic:dic];
                CommonCellViewModel* viewModel = [[CommonCellViewModel alloc] initWithCommonCellModel:model];
                [res addObject:viewModel];
            }
            
            if (weakSelf.engineModel.isNeedReloadData) {
                weakSelf.homeDataArr = res;
                weakSelf.engineModel.isNeedReloadData = NO;
            } else {
                [weakSelf.homeDataArr addObjectsFromArray:res];
            }
            
            [weakSelf updateNewGoodsCount];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableView reloadData];
                [weakSelf.tableView resetReloadMoreViewFrame];
                if (TableViewUpdateTypeRefresh == weakSelf.tableView.type) {
                    [weakSelf finishRefreshData];
                } else if (TableViewUpdateTypeReloadMore == weakSelf.tableView.type) {
                    [weakSelf finishReloadMoreDataWithIsEnd:(0 == count.integerValue)];
                }
                
                weakSelf.viewControllerType = ViewControllerNormalType;
            });
        }
    } errorHandler:^(NSError *errMsg) {
        NSLog(@"%@", errMsg);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableView resetReloadMoreViewFrame];
            if (TableViewUpdateTypeRefresh == weakSelf.tableView.type) {
                [weakSelf finishRefreshData];
            } else if (TableViewUpdateTypeReloadMore == weakSelf.tableView.type) {
                [weakSelf finishReloadMoreDataWithIsEnd:NO];
            }
            
            weakSelf.viewControllerType = ViewControllerNoNetWorkType;
        });
    }];
}

- (void)updateHomeFocus {
    if (_focusOperation.isExecuting) {
        return;
    }
    
    NSString* path = [[CommonEngine sharedInstance] urlPathForFocus];
    
    __weak typeof(self) weakSelf = self;
    _focusOperation = [[CommonEngine sharedInstance] getOperationWithURLPath:path shouldCache:NO completionHandler:^(NSDictionary *result) {
        
        NSNumber* status = [result objectForKey:@"status"];
        if (1 == status.integerValue) {
            [weakSelf.homeFocusArr removeAllObjects];
            NSArray* res = [result objectForKey:@"res"];
            for (NSDictionary* dic in res) {
                if ([[dic objectForKey:@"type"] isEqualToString:@"data"]) {
                    FocusModel* model = [[FocusModel alloc] initWithDic:dic];
                    FocusViewModel* viewModel = [[FocusViewModel alloc] initWithFocusModel:model];
                    [weakSelf.homeFocusArr addObject:viewModel];
                }
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf setHeaderViewScrollView];
                weakSelf.viewControllerType = ViewControllerNormalType;
            });
        }
        
    } errorHandler:^(NSError *errMsg) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.viewControllerType = ViewControllerNoNetWorkType;
        });
        
    }];
}

- (void)updateNewGoodsCount {
    if (_upnumOperation.isExecuting) {
        return;
    }
    
    NSString* recordDataStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"updateNewGoodsDate"];
    
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    NSString* nowStr = [formatter stringFromDate:[NSDate date]];
    
    if (![nowStr isEqualToString:recordDataStr]) {
        NSString* path = [[CommonEngine sharedInstance] urlPathForUpnum];
        
        __weak typeof(self) weakSelf = self;
        _upnumOperation = [[CommonEngine sharedInstance] getOperationWithURLPath:path shouldCache:NO completionHandler:^(NSDictionary *result) {
            NSNumber* status = [result objectForKey:@"status"];
            if (1 == status.integerValue) {
                NSArray* res = [result objectForKey:@"res"];
                NSDictionary* dic = res.firstObject;
                
                NSString* date = [dic objectForKey:@"date"];
                NSString* num = [dic objectForKey:@"num"];
                
                [[NSUserDefaults standardUserDefaults] setObject:date forKey:@"updateNewGoodsDate"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    weakSelf.updateView.updateCount = num;
                    [weakSelf showUpdateView];
                });
            }
        } errorHandler:^(NSError *errMsg) {
        }];
    }
}

- (void)showUpdateView {
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:.5 animations:^{
        if (8.0 <= [UIDevice currentDevice].systemVersion.floatValue) {
            weakSelf.updateView.transform = CGAffineTransformMakeTranslation(0, 29);
        } else {
            CGRect frame = weakSelf.updateView.frame;
            frame.origin.y = 28 + 29;
            weakSelf.updateView.frame = frame;
        }
    } completion:^(BOOL finished) {
        NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(closeUpdateView) userInfo:nil repeats:NO];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    }];
}

- (void)closeUpdateView {
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:.5 animations:^{
        if (8.0 <= [UIDevice currentDevice].systemVersion.floatValue) {
            weakSelf.updateView.transform = CGAffineTransformIdentity;
        } else {
            CGRect frame = weakSelf.updateView.frame;
            frame.origin.y = 28;
            weakSelf.updateView.frame = frame;
        }
    }];
}

- (void)setHeaderViewScrollView {
    [self.headerView clearScrollViewSubviews];
    
    for (NSInteger index = 0; index < self.homeFocusArr.count; ++index) {
        FocusViewModel* viewModel = [self.homeFocusArr objectAtIndex:index];
        
        FocusControl* focusCtrl = [[FocusControl alloc] initWithFrame:CGRectMake(CGRectGetWidth(_headerView.frame) * index, 0, CGRectGetWidth(_headerView.frame), CGRectGetHeight(_headerView.scrollView.frame))];
        focusCtrl.backgroundColor = [UIColor clearColor];
        focusCtrl.viewModel = viewModel;
        [self.headerView.scrollView addSubview:focusCtrl];
        
        __weak typeof(self) weakSelf = self;
        focusCtrl.tapControlHandler = ^(FocusViewModel* viewModel) {
            CustomTableViewController* controller = [self.storyboard instantiateViewControllerWithIdentifier:@"CustomTableViewController"];
            controller.title = viewModel.title;
            controller.urlPath = viewModel.urlPath;
            controller.type = CustomTableViewControllerTypeFocus;
            [weakSelf.navigationController pushViewController:controller animated:YES];
//            [weakSelf.tabBarController setTabBarHidden:YES animated:YES];
        };
    }
    
    _headerView.scrollView.contentSize = CGSizeMake(CGRectGetWidth(_headerView.frame) * self.homeFocusArr.count, 257 / 2.0);
    _headerView.scrollView.delegate = self;
    _headerView.pageControl.numberOfPages = self.homeFocusArr.count;
}

- (void)scrollingHeaderViewScrollViewToNextImage {
    NSInteger page = self.headerView.pageControl.currentPage;
    if (page == self.homeFocusArr.count - 1) {
        page = 0;
    } else {
        page++;
    }
    
    CGFloat x = page * CGRectGetWidth(self.headerView.scrollView.frame);
    [self.headerView.scrollView setContentOffset:CGPointMake(x, 0) animated:YES];
}

- (void)headerViewScrollViewAddTimer {
    self.autoScrollingtime = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(scrollingHeaderViewScrollViewToNextImage) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.autoScrollingtime forMode:NSRunLoopCommonModes];
}

- (void)headerViewScrollViewRemoveTimer {
    [self.autoScrollingtime invalidate];
}

#pragma mark - IBAction
- (IBAction)onTapMoreBtn:(id)sender {
//    [self.tabBarController setTabBarHidden:YES animated:YES];
}

- (IBAction)onTapSettingBtn:(id)sender {
//    [self.tabBarController setTabBarHidden:YES animated:YES];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.homeDataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CommonTableViewCell *cell = (CommonTableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"HomeCell"];
    
    CommonCellViewModel* viewModel = [self.homeDataArr objectAtIndex:indexPath.row];
    
    [cell layoutSubviewDataWithViewModel:viewModel];
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    CommonTableViewCell* cell = (CommonTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
    if (cell.isSwiping) {
        return;
    }
    
    CommonCellViewModel* viewModel = [self.homeDataArr objectAtIndex:indexPath.row];
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    DetailViewController* controller = [self.storyboard instantiateViewControllerWithIdentifier:@"DetailViewController"];
    controller.currentGoodsViewModel = viewModel;
    [self.navigationController pushViewController:controller animated:YES];
//    [self.tabBarController setTabBarHidden:YES animated:YES];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if ([scrollView isEqual:self.headerView.scrollView]) {
        [self headerViewScrollViewRemoveTimer];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if ([scrollView isEqual:self.headerView.scrollView]) {
        [self headerViewScrollViewAddTimer];
    } else {
        [super scrollViewDidEndDragging:scrollView willDecelerate:decelerate];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if ([scrollView isEqual:self.headerView.scrollView]) {
        CGFloat width = CGRectGetWidth(scrollView.frame);
        CGFloat offsetX = scrollView.contentOffset.x;
        
        NSInteger page = (offsetX + width / 2) / width;
        self.headerView.pageControl.currentPage = page;
    } else {
        [super scrollViewDidScroll:scrollView];
    }
}

#pragma mark - ReloadMoreDropupViewDelegate
- (void)reloadMoreDropupViewWillReloadData:(ReloadMoreDropupView *)reloadMoreDropupView {
    self.isUpdateFocus = NO;
    
    [super reloadMoreDropupViewWillReloadData:reloadMoreDropupView];
}

@end
